package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class GetConstructor {
    /*
    #通过反射获取所有构造方法
        Constructor[] getConstructors()
        Constructor[] getDeclaredConstructors()
    #获取指定构造方法
        Constructor<T> getConstructor(Class<?>... parameterTypes)
        Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //1.Class类中用于获取构造方法的方法

        //1.获取class字节码文件对象
        Class clazz = Class.forName("reflect.Student");

        //2.获取构造方法:只能获取public
        Constructor[] cons = clazz.getConstructors();
        for (Constructor c : cons) {
            System.out.println(c);
        }
        System.out.println("******************");
        //3.获取构造方法：能获取所有权限的构造方法
        Constructor[] cons2 = clazz.getDeclaredConstructors();
        for (Constructor c : cons2) {
            System.out.println(c);
        }
        System.out.println("******************");
        //4.获取空参构造
        Constructor con = clazz.getDeclaredConstructor();
        System.out.println(con);
        //5.获取指定的有参构造
        Constructor con2 = clazz.getDeclaredConstructor(String.class);
        System.out.println(con2);
        //6.获取两个参数的
        Constructor<Student> con3 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(con3);
        System.out.println("******************");
        //获取方法的权限修饰符
        int modifiers = clazz.getDeclaredConstructor().getModifiers();
        System.out.println(modifiers);

        con3.setAccessible(true);//临时取消权限校验，暴力反射
        Student s = con3.newInstance("zx",23);
        System.out.println(s);


    }
}
class Student {
    private String name;
    private int age;

    public Student() {
    }
    private Student(String name) {
        this.name = name;
    }
    private Student(int age) {
        this.age = age;
    }

    private Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
